/**
 * @author EasonChan
 *
 * Nov 19, 2010
 */
package com.musicgeek.util;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.commons.codec.binary.Base64;

/**
 * Helper class for encryption,decryption,encoding and decoding.
 */
public class SecurityUtil {

	/**
	 * @param data
	 *            The data to be process.
	 * @param algorithm
	 *            The algorithm uesd to get digest
	 * @param radix
	 *            radix which the digest ouput base upon
	 * @return The digest
	 */
	public static String getDigest(String data, String algorithm, int radix) {
		byte[] dataInBytes = data.getBytes();
		String digest = null;
		MessageDigest messageDigest;
		try {
			messageDigest = MessageDigest.getInstance(algorithm);
			messageDigest.update(dataInBytes);
			// 1 for positive sign-magnitude
			digest = new BigInteger(1, messageDigest.digest()).toString(radix);
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return digest;
	}

	/**
	 * @param data
	 *            The data to be Encrypt using BASE64 algorithm
	 * @return Encoded data
	 */
	public static String encodeBase64(String data) {
		byte[] encodedBytes = Base64.encodeBase64(data.getBytes());
		return new String(encodedBytes);
	}

	/**
	 * @param base64String
	 *            The BASE64 encoded string that need to be decode.
	 * @return Decoded data
	 */
	public static String decodeBase64(String base64String) {
		byte[] decodedBytes = Base64.decodeBase64(base64String);
		return new String(decodedBytes);
	}

}
